package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.StockWarning;
import com.geek.factory.entity.Material;
import com.geek.factory.entity.PurchaseOrder;
import com.geek.factory.entity.PurchaseOrderDetail;
import com.geek.factory.entity.MaterialSupplier;
import com.geek.factory.result.Result;
import com.geek.factory.service.*;
import com.geek.factory.service.scheduler.StockWarningScheduler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geek.factory.entity.InventoryDistribution;
import com.geek.factory.entity.Warehouse;
import com.geek.factory.entity.Shelves;
import com.geek.factory.entity.Supplier;


/**
 * 库存预警控制器
 */
@RestController
@RequestMapping("/stock-alert")
@Api(tags = "后台系统的 - 库存预警模块")
@Slf4j
@CrossOrigin
public class StockWarningController {

    @Autowired
    private IStockWarningService stockWarningService;
    
    @Autowired
    private StockWarningScheduler stockWarningScheduler;
    
    @Autowired
    private IMaterialService materialService;
    
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    
    @Autowired
    private IPurchaseOrderDetailService purchaseOrderDetailService;
    
    @Autowired
    private MaterialSupplierService materialSupplierService;

    @Autowired
    private IInventoryDistributionService inventoryDistributionService;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IShelvesService shelvesService;
    
    @Autowired
    private SupplierService supplierService;
    
    @ApiOperation("分页查询库存预警")
    @GetMapping("/page")
    public Result getStockWarningPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("物品类型") @RequestParam(required = false) String itemType,
            @ApiParam("预警类型") @RequestParam(required = false) String alertType,
            @ApiParam("预警状态") @RequestParam(required = false) String status
    ) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<StockWarning> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加条件
            if (itemType != null && !itemType.isEmpty()) {
                // 将前端的itemType映射到后端的itemType
                String dbItemType = itemType;
                if ("product".equals(itemType) || "产品".equals(itemType)) {
                    dbItemType = "product";
                } else if ("material".equals(itemType) || "原料".equals(itemType)) {
                    dbItemType = "material";
                }
                queryWrapper.eq(StockWarning::getItemType, dbItemType);
            }
            if (alertType != null && !alertType.isEmpty()) {
                // 将前端的alertType映射到后端的warningType
                String warningType = alertType;
                if ("insufficient".equals(alertType) || "库存不足".equals(alertType)) {
                    warningType = StockWarningScheduler.WARNING_TYPE_INSUFFICIENT;
                } else if ("excess".equals(alertType) || "库存积压".equals(alertType)) {
                    warningType = StockWarningScheduler.WARNING_TYPE_EXCESS;
                }
                queryWrapper.eq(StockWarning::getWarningType, warningType);
            }
            if (status != null && !status.isEmpty()) {
                // 将前端的status映射到后端的status
                String dbStatus = status;
                if ("unread".equals(status) || "未读".equals(status)) {
                    dbStatus = StockWarningScheduler.WARNING_STATUS_UNREAD;
                } else if ("read".equals(status) || "已读".equals(status)) {
                    dbStatus = StockWarningScheduler.WARNING_STATUS_READ;
                } else if ("processed".equals(status) || "已处理".equals(status)) {
                    dbStatus = StockWarningScheduler.WARNING_STATUS_PROCESSED;
                }
                queryWrapper.eq(StockWarning::getStatus, dbStatus);
            }
            
            // 按时间倒序排序
            queryWrapper.orderByDesc(StockWarning::getWarningTime);
            
            // 执行分页查询
            Page<StockWarning> page = stockWarningService.page(new Page<>(current, size), queryWrapper);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", page.getRecords());
            result.put("total", page.getTotal());
            result.put("size", page.getSize());
            result.put("current", page.getCurrent());
            result.put("pages", page.getPages());
            
            return new Result(SuccessConstant.SUCCESS, "查询成功", result);
        } catch (Exception e) {
            log.error("查询库存预警失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取未读预警数量")
    @GetMapping("/unread-count")
    public Result getUnreadAlertCount() {
        try {
            LambdaQueryWrapper<StockWarning> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StockWarning::getStatus, StockWarningScheduler.WARNING_STATUS_UNREAD);
            
            long count = stockWarningService.count(queryWrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            
            return new Result(SuccessConstant.SUCCESS, "查询成功", result);
        } catch (Exception e) {
            log.error("查询未读预警数量失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("标记预警为已读")
    @PutMapping("/{id}/read")
    public Result markAsRead(@ApiParam("预警ID") @PathVariable Integer id) {
        try {
            if (id == null) {
                return new Result(SuccessConstant.FAIL, "预警ID不能为空");
            }
            
            LambdaUpdateWrapper<StockWarning> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StockWarning::getWarningId, id)
                        .set(StockWarning::getStatus, StockWarningScheduler.WARNING_STATUS_READ);
            
            boolean success = stockWarningService.update(updateWrapper);
            
            if (success) {
                return new Result(SuccessConstant.SUCCESS, "标记成功");
            } else {
                return new Result(SuccessConstant.FAIL, "标记失败，预警不存在");
            }
        } catch (Exception e) {
            log.error("标记预警为已读失败", e);
            return new Result(SuccessConstant.FAIL, "标记失败: " + e.getMessage());
        }
    }

    @ApiOperation("标记预警为已处理")
    @PutMapping("/{id}/handle")
    public Result markAsHandled(@ApiParam("预警ID") @PathVariable Integer id) {
        try {
            if (id == null) {
                return new Result(SuccessConstant.FAIL, "预警ID不能为空");
            }
            
            LambdaUpdateWrapper<StockWarning> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StockWarning::getWarningId, id)
                        .set(StockWarning::getStatus, StockWarningScheduler.WARNING_STATUS_PROCESSED);
            
            boolean success = stockWarningService.update(updateWrapper);
            
            if (success) {
                return new Result(SuccessConstant.SUCCESS, "标记成功");
            } else {
                return new Result(SuccessConstant.FAIL, "标记失败，预警不存在");
            }
        } catch (Exception e) {
            log.error("标记预警为已处理失败", e);
            return new Result(SuccessConstant.FAIL, "标记失败: " + e.getMessage());
        }
    }

    /**
     * 处理前端传递undefined作为ID的情况
     */
    @ApiOperation("标记预警为已读 - 处理undefined")
    @PutMapping("/undefined/read")
    public Result handleUndefinedRead() {
        log.warn("前端传递了undefined作为ID，请检查前端代码");
        return new Result(SuccessConstant.FAIL, "预警ID不能为空或undefined");
    }

    /**
     * 处理前端传递undefined作为ID的情况
     */
    @ApiOperation("标记预警为已处理 - 处理undefined")
    @PutMapping("/undefined/handle")
    public Result handleUndefinedHandle() {
        log.warn("前端传递了undefined作为ID，请检查前端代码");
        return new Result(SuccessConstant.FAIL, "预警ID不能为空或undefined");
    }

    // 保留原有的方法，以兼容可能存在的其他调用
    @ApiOperation("标记预警为已读")
    @PutMapping("/{warningId}/mark-read")
    public Result markWarningAsRead(@ApiParam("预警ID") @PathVariable Integer warningId) {
        try {
            LambdaUpdateWrapper<StockWarning> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StockWarning::getWarningId, warningId)
                        .set(StockWarning::getStatus, StockWarningScheduler.WARNING_STATUS_READ);
            
            boolean success = stockWarningService.update(updateWrapper);
            
            if (success) {
                return new Result(SuccessConstant.SUCCESS, "标记成功");
            } else {
                return new Result(SuccessConstant.FAIL, "标记失败，预警不存在");
            }
        } catch (Exception e) {
            log.error("标记预警为已读失败", e);
            return new Result(SuccessConstant.FAIL, "标记失败: " + e.getMessage());
        }
    }

    @ApiOperation("批量标记预警为已读")
    @PutMapping("/batch/mark-read")
    public Result batchMarkWarningsAsRead(@RequestBody List<Integer> warningIds) {
        try {
            if (warningIds == null || warningIds.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "请选择要标记的预警");
            }
            
            LambdaUpdateWrapper<StockWarning> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(StockWarning::getWarningId, warningIds)
                        .set(StockWarning::getStatus, StockWarningScheduler.WARNING_STATUS_READ);
            
            boolean success = stockWarningService.update(updateWrapper);
            
            if (success) {
                return new Result(SuccessConstant.SUCCESS, "批量标记成功");
            } else {
                return new Result(SuccessConstant.FAIL, "批量标记失败");
            }
        } catch (Exception e) {
            log.error("批量标记预警为已读失败", e);
            return new Result(SuccessConstant.FAIL, "批量标记失败: " + e.getMessage());
        }
    }

    @ApiOperation("手动触发库存预警检查")
    @PostMapping("/check-now")
    public Result manualCheckStockWarnings() {
        try {
            // 执行库存预警检查并获取结果
            Map<String, Object> checkResult = stockWarningScheduler.manualCheckStockWarnings();
            
            return new Result(SuccessConstant.SUCCESS, "库存预警检查已完成", checkResult);
        } catch (Exception e) {
            log.error("手动触发库存预警检查失败", e);
            return new Result(SuccessConstant.FAIL, "触发失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成采购单编码
     */
    private String generatePurchaseOrderCode() {
        String prefix = "PO";  // PO = Purchase Order
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }
    
    @ApiOperation(value = "根据库存预警生成采购单", notes = "根据选中的库存预警自动生成采购单，支持自定义采购数量。\n" +
            "请求体格式：{\n" +
            "  \"warningIds\": [1, 2, 3],  // 必填，预警ID列表\n" +
            "  \"customQuantities\": {      // 可选，自定义采购数量，key为预警ID，value为采购数量\n" +
            "    \"1\": 100,\n" +
            "    \"2\": 200\n" +
            "  }\n" +
            "}")
    @PostMapping("/generate-purchase-order")
    @Transactional
    public Result generatePurchaseOrderFromWarning(@RequestBody Map<String, Object> requestData) {
        try {
            // 获取预警ID列表
            List<Integer> warningIds = (List<Integer>) requestData.get("warningIds");
            // 获取自定义数量映射（可选）
            Map<Integer, Integer> customQuantities = (Map<Integer, Integer>) requestData.get("customQuantities");
            
            if (warningIds == null || warningIds.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "请选择要处理的预警");
            }
            
            // 1. 查询选中的预警记录
            List<StockWarning> warnings = stockWarningService.listByIds(warningIds);
            if (warnings.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "未找到有效的预警记录");
            }
            
            // 2. 筛选出库存不足的原料预警
            List<StockWarning> materialWarnings = warnings.stream()
                .filter(w -> "material".equals(w.getItemType()) && 
                       StockWarningScheduler.WARNING_TYPE_INSUFFICIENT.equals(w.getWarningType()))
                .collect(Collectors.toList());
            
            if (materialWarnings.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "未找到有效的原料库存不足预警");
            }
            
            // 3. 创建采购单主表 - 只设置必要的字段
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            purchaseOrder.setOrderNo(generatePurchaseOrderCode());
            purchaseOrder.setOrderDate(LocalDate.now());
            purchaseOrder.setStatus("草稿"); // 设置为草稿状态，表示需要手动完善
            purchaseOrder.setAmount(BigDecimal.ZERO); // 设置初始金额为0
            purchaseOrder.setCreatedTime(LocalDateTime.now());
            purchaseOrder.setCreatedBy("system"); // 可以根据实际登录用户修改
            
            // 设置默认供应商ID，防止数据库错误
            // 查找第一个原料的供应商
            for (StockWarning warning : materialWarnings) {
                Material material = materialService.getById(warning.getItemId());
                if (material != null) {
                    List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                        .eq(MaterialSupplier::getMaterialId, material.getMaterialId())
                        .orderByAsc(MaterialSupplier::getUnitPrice)
                        .list();
                    
                    if (suppliers != null && !suppliers.isEmpty()) {
                        // 使用第一个供应商的ID作为默认值
                        purchaseOrder.setSupplierId(suppliers.get(0).getSupplierId());
                        
                        // 查询供应商详细信息
                        Supplier supplierInfo = supplierService.getById(suppliers.get(0).getSupplierId());
                        if (supplierInfo != null) {
                            purchaseOrder.setSupplierName(supplierInfo.getSupplierName());
                        }
                        
                        break; // 找到一个供应商后就退出循环
                    }
                }
            }
            
            // 如果没有找到任何供应商，设置一个默认值防止数据库错误
            if (purchaseOrder.getSupplierId() == null) {
                purchaseOrder.setSupplierId(1); // 设置一个默认值，避免数据库错误
            }
            
            // 4. 保存采购单主表
            boolean saved = purchaseOrderService.save(purchaseOrder);
            if (!saved) {
                return new Result(SuccessConstant.FAIL, "创建采购单失败");
            }
            
            // 5. 创建采购单明细 - 只包含基本信息
            List<Map<String, Object>> detailsInfo = new ArrayList<>();
            for (StockWarning warning : materialWarnings) {
                // 获取原料信息
                Material material = materialService.getById(warning.getItemId());
                if (material == null) {
                    log.warn("原料不存在，ID: {}", warning.getItemId());
                    continue;
                }
                
                // 计算采购数量
                BigDecimal purchaseQuantity;
                
                // 如果前端传入了自定义数量，则使用自定义数量
                if (customQuantities != null && customQuantities.containsKey(warning.getWarningId())) {
                    purchaseQuantity = new BigDecimal(customQuantities.get(warning.getWarningId()));
                } else {
                    // 否则使用默认计算方式：最小库存 - 当前库存
                    BigDecimal minStock = new BigDecimal(material.getMinStock());
                    BigDecimal currentStock = warning.getCurrentStock();
                    purchaseQuantity = minStock.subtract(currentStock);
                }
                
                if (purchaseQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                    log.warn("原料[{}]不需要采购，采购数量: {}", 
                            material.getMaterialName(), purchaseQuantity);
                    continue;
                }
                
                // 查找该原料的供应商关系
                List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                    .eq(MaterialSupplier::getMaterialId, material.getMaterialId())
                    .orderByAsc(MaterialSupplier::getUnitPrice) // 按价格升序，选择最低价
                    .list();
                
                // 为每个供应商添加名称
                if (suppliers != null && !suppliers.isEmpty()) {
                    for (MaterialSupplier supplier : suppliers) {
                        Supplier supplierInfo = supplierService.getById(supplier.getSupplierId());
                        if (supplierInfo != null) {
                            supplier.setSupplierName(supplierInfo.getSupplierName());
                        }
                    }
                }
                
                // 创建采购明细
                PurchaseOrderDetail detail = new PurchaseOrderDetail();
                detail.setPurchaseId(purchaseOrder.getOrderId());
                detail.setMaterialId(material.getMaterialId());
                detail.setQuantity(purchaseQuantity.intValue());
                
                // 如果找到供应商，设置单价
                if (suppliers != null && !suppliers.isEmpty()) {
                    MaterialSupplier supplier = suppliers.get(0);
                    detail.setUnitPrice(supplier.getUnitPrice());
                }
                
                // 保存采购明细
                purchaseOrderDetailService.save(detail);
                
                // 收集明细信息用于返回
                Map<String, Object> detailInfo = new HashMap<>();
                detailInfo.put("detailId", detail.getDetailId());
                detailInfo.put("materialId", material.getMaterialId());
                detailInfo.put("materialName", material.getMaterialName());
                detailInfo.put("materialCode", material.getMaterialCode());
                detailInfo.put("quantity", detail.getQuantity());
                detailInfo.put("unit", material.getUnit());
                detailInfo.put("suppliers", suppliers);
                detailsInfo.add(detailInfo);
                
                // 更新预警状态为已处理
                warning.setStatus(StockWarningScheduler.WARNING_STATUS_PROCESSED);
                stockWarningService.updateById(warning);
            }
            
            // 6. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("purchaseOrder", purchaseOrder);
            result.put("details", detailsInfo);
            result.put("warningCount", materialWarnings.size());
            
            return new Result(SuccessConstant.SUCCESS, "采购单生成成功", result);
            
        } catch (Exception e) {
            log.error("根据库存预警生成采购单失败", e);
            return new Result(SuccessConstant.FAIL, "生成采购单失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "获取补货建议", notes = "根据预警ID获取单个补货建议信息，包括建议采购数量和可选供应商")
    @GetMapping("/replenishment-suggestion/{warningId}")
    public Result getReplenishmentSuggestion(@PathVariable Integer warningId) {
        try {
            // 1. 获取预警信息
            StockWarning warning = stockWarningService.getById(warningId);
            if (warning == null) {
                return new Result(SuccessConstant.FAIL, "预警不存在");
            }
            
            // 2. 只处理原料的库存不足预警
            if (!"material".equals(warning.getItemType()) || 
                !StockWarningScheduler.WARNING_TYPE_INSUFFICIENT.equals(warning.getWarningType())) {
                return new Result(SuccessConstant.FAIL, "只支持原料的库存不足预警");
            }
            
            // 3. 获取原料信息
            Material material = materialService.getById(warning.getItemId());
            if (material == null) {
                return new Result(SuccessConstant.FAIL, "原料不存在");
            }
            
            // 4. 计算建议采购数量 = 最小库存 - 当前库存
            BigDecimal minStock = new BigDecimal(material.getMinStock());
            BigDecimal currentStock = warning.getCurrentStock();
            BigDecimal suggestedQuantity = minStock.subtract(currentStock);
            
            if (suggestedQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                return new Result(SuccessConstant.FAIL, "当前库存已满足最小库存要求，无需补货");
            }
            
            // 5. 查找该原料的供应商关系
            List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                .eq(MaterialSupplier::getMaterialId, material.getMaterialId())
                .orderByAsc(MaterialSupplier::getUnitPrice) // 按价格升序
                .list();
                
            // 为每个供应商添加名称信息
            if (suppliers != null && !suppliers.isEmpty()) {
                for (MaterialSupplier supplier : suppliers) {
                    // 查询供应商详细信息
                    Supplier supplierInfo = supplierService.getById(supplier.getSupplierId());
                    if (supplierInfo != null) {
                        // 添加供应商名称
                        supplier.setSupplierName(supplierInfo.getSupplierName());
                    }
                }
            }
            
            // 6. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("warningId", warning.getWarningId());
            result.put("materialId", material.getMaterialId());
            result.put("materialName", material.getMaterialName());
            result.put("materialCode", material.getMaterialCode());
            result.put("currentStock", currentStock);
            result.put("minStock", minStock);
            result.put("suggestedQuantity", suggestedQuantity);
            result.put("unit", material.getUnit());
            result.put("suppliers", suppliers != null ? suppliers : new ArrayList<>());
            
            return new Result(SuccessConstant.SUCCESS, "获取成功", result);
            
        } catch (Exception e) {
            log.error("获取补货建议失败", e);
            return new Result(SuccessConstant.FAIL, "获取补货建议失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "批量获取补货建议", notes = "根据选中的库存预警ID列表，批量获取补货建议信息，包括建议采购数量和可选供应商。\n" +
            "请求体格式：[1, 2, 3]  // 预警ID列表")
    @PostMapping("/batch/replenishment-suggestion")
    public Result getBatchReplenishmentSuggestion(@RequestBody List<Integer> warningIds) {
        try {
            if (warningIds == null || warningIds.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "请选择要处理的预警");
            }
            
            // 1. 查询选中的预警记录
            List<StockWarning> warnings = stockWarningService.listByIds(warningIds);
            if (warnings.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "未找到有效的预警记录");
            }
            
            // 2. 筛选出库存不足的原料预警
            List<StockWarning> materialWarnings = warnings.stream()
                .filter(w -> "material".equals(w.getItemType()) && 
                       StockWarningScheduler.WARNING_TYPE_INSUFFICIENT.equals(w.getWarningType()))
                .collect(Collectors.toList());
            
            if (materialWarnings.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "未找到有效的原料库存不足预警");
            }
            
            // 3. 计算每个预警的补货建议
            List<Map<String, Object>> suggestions = new ArrayList<>();
            for (StockWarning warning : materialWarnings) {
                // 获取原料信息
                Material material = materialService.getById(warning.getItemId());
                if (material == null) {
                    log.warn("原料不存在，ID: {}", warning.getItemId());
                    continue;
                }
                
                // 计算建议采购数量 = 最小库存 - 当前库存
                BigDecimal minStock = new BigDecimal(material.getMinStock());
                BigDecimal currentStock = warning.getCurrentStock();
                BigDecimal suggestedQuantity = minStock.subtract(currentStock);
                
                if (suggestedQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                    log.warn("原料[{}]不需要补货，最小库存: {}，当前库存: {}", 
                            material.getMaterialName(), minStock, currentStock);
                    continue;
                }
                
                // 查找该原料的供应商关系
                List<MaterialSupplier> suppliers = materialSupplierService.lambdaQuery()
                    .eq(MaterialSupplier::getMaterialId, material.getMaterialId())
                    .orderByAsc(MaterialSupplier::getUnitPrice) // 按价格升序
                    .list();
                
                // 构建建议信息
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("warningId", warning.getWarningId());
                suggestion.put("materialId", material.getMaterialId());
                suggestion.put("materialName", material.getMaterialName());
                suggestion.put("materialCode", material.getMaterialCode());
                suggestion.put("currentStock", currentStock);
                suggestion.put("minStock", minStock);
                suggestion.put("suggestedQuantity", suggestedQuantity);
                suggestion.put("unit", material.getUnit());
                
                // 处理供应商信息，确保前端显示正确
                if (suppliers != null && !suppliers.isEmpty()) {
                    // 为每个供应商对象添加必要的信息
                    for (MaterialSupplier supplier : suppliers) {
                        // 查询供应商详细信息
                        com.geek.factory.entity.Supplier supplierInfo = supplierService.getById(supplier.getSupplierId());
                        if (supplierInfo != null) {
                            // 添加供应商名称等信息
                            supplier.setSupplierName(supplierInfo.getSupplierName());
                        }
                    }
                    suggestion.put("suppliers", suppliers);
                } else {
                    suggestion.put("suppliers", new ArrayList<>());
                }
                
                suggestions.add(suggestion);
            }
            
            return new Result(SuccessConstant.SUCCESS, "获取成功", suggestions);
            
        } catch (Exception e) {
            log.error("批量获取补货建议失败", e);
            return new Result(SuccessConstant.FAIL, "获取补货建议失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "获取预警物品的库存分布详情", notes = "根据预警ID获取物品在各个仓库和货柜的分布情况")
    @GetMapping("/{warningId}/inventory-distribution")
    public Result getWarningItemDistribution(@PathVariable Integer warningId) {
        try {
            // 1. 获取预警信息
            StockWarning warning = stockWarningService.getById(warningId);
            if (warning == null) {
                return new Result(SuccessConstant.FAIL, "预警不存在");
            }
            
            // 2. 根据物品类型和ID查询库存分布
            QueryWrapper<InventoryDistribution> wrapper = new QueryWrapper<>();
            if ("product".equals(warning.getItemType())) {
                wrapper.eq("product_id", warning.getItemId());
            } else if ("material".equals(warning.getItemType())) {
                wrapper.eq("material_id", warning.getItemId());
            } else {
                return new Result(SuccessConstant.FAIL, "不支持的物品类型: " + warning.getItemType());
            }
            
            // 3. 按仓库和货柜排序
            wrapper.orderByAsc("warehouse_id", "shelf_id");
            
            // 4. 查询库存分布
            List<InventoryDistribution> distributions = inventoryDistributionService.list(wrapper);
            
            // 5. 丰富数据，添加仓库和货柜信息
            List<Map<String, Object>> enrichedDistributions = new ArrayList<>();
            for (InventoryDistribution distribution : distributions) {
                Map<String, Object> enriched = new HashMap<>();
                enriched.put("distributionId", distribution.getDistributionId());
                enriched.put("quantity", distribution.getQuantity());
                
                // 添加仓库信息
                if (distribution.getWarehouseId() != null) {
                    Warehouse warehouse = warehouseService.getById(distribution.getWarehouseId());
                    if (warehouse != null) {
                        enriched.put("warehouseId", warehouse.getWarehouseId());
                        enriched.put("warehouseName", warehouse.getWarehouseName());
                        enriched.put("warehouseCode", warehouse.getWarehouseCode());
                    }
                }
                
                // 添加货柜信息
                if (distribution.getShelfId() != null) {
                    Shelves shelf = shelvesService.getById(distribution.getShelfId());
                    if (shelf != null) {
                        enriched.put("shelfId", shelf.getShelfId());
                        enriched.put("shelfName", shelf.getShelfName());
                        enriched.put("shelfCode", shelf.getShelfCode());
                        enriched.put("locationCode", shelf.getLocationCode());
                    }
                }
                
                enrichedDistributions.add(enriched);
            }
            
            // 6. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("warningId", warning.getWarningId());
            result.put("itemId", warning.getItemId());
            result.put("itemType", warning.getItemType());
            result.put("itemName", warning.getItemName());
            result.put("itemCode", warning.getItemCode());
            result.put("currentStock", warning.getCurrentStock());
            result.put("thresholdValue", warning.getThresholdValue());
            result.put("unit", warning.getUnit());
            result.put("distributions", enrichedDistributions);
            
            return new Result(SuccessConstant.SUCCESS, "查询成功", result);
            
        } catch (Exception e) {
            log.error("获取预警物品库存分布详情失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }
}
